/* Copyright (c) [2025] [zhi1208@126.com]
 * SPDX-License-Identifier: MIT
 */

/*********************
 *      INCLUDES
 *********************/
#include "lvgl.h"
#include "hmi_png.h"
#include "hmi_config.h"
/*********************
 *      DEFINES
 *********************/

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/
static void loading_toast_close_anim_exec_xcb(void *var, int32_t val);
static void loading_toast_close_anim_completed_cb(lv_anim_t *a);

/**********************
 *  STATIC VARIABLES
 **********************/
static lv_obj_t *loading_toast;

/**********************
 *      MACROS
 **********************/

/**********************
 *   GLOBAL FUNCTIONS
 **********************/
void hmi_loading_toast_open()
{
    if (loading_toast)
        return;

    loading_toast = lv_obj_create(lv_layer_top());
    lv_obj_remove_style_all(loading_toast);
    lv_obj_set_style_bg_opa(loading_toast, LV_OPA_60, 0);
    lv_obj_set_style_bg_color(loading_toast, lv_palette_darken(LV_PALETTE_GREY, 3), 0);
    lv_obj_set_size(loading_toast, 80, 80);
    lv_obj_set_style_radius(loading_toast, 10, 0);
    lv_obj_center(loading_toast);

    lv_obj_t *loading_toast_icon = lv_image_create(loading_toast);
    lv_obj_center(loading_toast_icon);
    lv_image_set_src(loading_toast_icon, hmi_png("rays"));
    lv_image_set_scale(loading_toast_icon, 300);

    lv_anim_t a;
    lv_anim_init(&a);
    lv_anim_set_var(&a, loading_toast_icon);
    lv_anim_set_duration(&a, 1000);
    lv_anim_set_exec_cb(&a, (lv_anim_exec_xcb_t)lv_image_set_rotation);
    lv_anim_set_values(&a, 0, 3600);
    lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE);
    lv_anim_start(&a);

    lv_obj_fade_in(loading_toast, HMI_ANIM_TIME, 0);
}

void hmi_loading_toast_close()
{
    if (!loading_toast)
        return;

    lv_anim_t a;
    lv_anim_init(&a);
    lv_anim_set_var(&a, loading_toast);
    lv_anim_set_duration(&a, HMI_ANIM_TIME);
    lv_anim_set_exec_cb(&a, loading_toast_close_anim_exec_xcb);
    lv_anim_set_values(&a, LV_OPA_COVER, LV_OPA_TRANSP);
    lv_anim_set_completed_cb(&a, loading_toast_close_anim_completed_cb);
    lv_anim_start(&a);
}

/**********************
 *   STATIC FUNCTIONS
 **********************/
static void loading_toast_close_anim_exec_xcb(void *var, int32_t val)
{
    lv_obj_set_style_bg_opa(var, val, 0);
}

static void loading_toast_close_anim_completed_cb(lv_anim_t *a)
{
    LV_UNUSED(a);
    lv_obj_del(loading_toast);
    loading_toast = NULL;
}